<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item  prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入团购主键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择团购状态" clearable>
          <el-option
            v-for="dict in dict.type.group_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="storageId">
        <el-select v-model="queryParams.storageId" placeholder="请选择前置仓" clearable>
          <el-option v-for="item in storages" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['group:groupShop:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupShopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="true"/>
      <el-table-column label="仓库" align="center" prop="storageName">
        <template slot-scope="scope">
          {{ storageMap[scope.row.storageId] }}
        </template>
      </el-table-column>
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="团购开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="团购结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="团购基础人数" align="center" prop="minimumNumber" />
      <el-table-column label="团购已经购买人数" align="center" prop="alreadyBuyNumber" />
      <el-table-column label="到期未达到基础人数,是否自动退款" align="center" prop="automaticRefund">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.automaticRefund == 1 ? 'success' : 'error' "
          >{{ scope.row.automaticRefund == 1 ? '退款' : '发货' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.group_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['group:groupShop:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['group:groupShop:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-card class="box-card">
        <h3>商品属性(spu)</h3>
        <el-form
          ref="form"
          :rules="rules"
          :model="form"
          status-icon
          label-position="left"
          label-width="150px"
          style="width: 700px; margin-left:50px;"
        >
          <el-form-item label="仓库选择">
            <el-select v-model="form.storageId" placeholder="请选择团购仓库" clearable filterable @change="showEditStorageChange" @click.native="showEditStorageClick">
              <el-option
                v-for="item in storages"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="团购商品">
            <el-cascader
              v-model="goodsOption"
              :options="goodsOptions"
              placeholder="团购商品"
              filterable
              clearable
              @change="chooseGoods" />
          </el-form-item>

          <el-form-item label="团购时间">
            <el-col :span="11" >
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;" />
            </el-col>
            <el-col :span="1" class="line" style="margin-left: 10px">&nbsp;&nbsp;&nbsp;&nbsp; 至</el-col>
            <el-col :span="11">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;" />
            </el-col>
          </el-form-item>

          <el-form-item label="团购基础人数" >
            <el-input-number v-model="form.minimumNumber" :precision="0" clearable controls-position="right" />
          </el-form-item>

          <el-form-item label="活动结束时人数没有达到基础人数处理">
            <el-radio-group v-model="form.automaticRefund" >
              <el-radio-button :label="1">自动退款,我不发货</el-radio-button>
              <el-radio-button :label="0">不退款,我要发货</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="box-card">
        <h3>商品类型(sku)</h3>
        <!-- <el-button :plain="true" type="primary" @click="handleSkuShow">添加</el-button> -->
        <el-table :data="form.skuList">
          <el-table-column property="id" label="SkuId"/>
          <el-table-column property="title" label="类型名" />
          <el-table-column property="stock" label="库存" />
          <el-table-column property="price" label="现价/元" />
          <el-table-column property="productGroupShopPrice" label="团购价格/元" />
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="openSkuGroupShopPriceUpdateDialog(scope.row)">更新</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 更新团购价格的Dialog -->
      <el-dialog :visible.sync="groupShopUpdateSkuPriceDialog" :modal="true" :append-to-body="true" :close-on-click-modal = "false" top="10vh" width="70%" title="更新团购价格">
        <el-form
          ref="specForm"
          :model="skuForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="团购价格" >
            <el-input-number v-model="skuForm.productGroupShopPrice" :precision="2" clearable controls-position="right" />元
          </el-form-item>
          <el-form-item label="现价">
            {{ skuForm.price }}元
          </el-form-item>
          <el-form-item label="sku类型名">
            {{ skuForm.title }}元
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="groupShopUpdateSkuPriceDialog = false">取消</el-button>
          <el-button type="primary" @click="skuGroupShopUpdate()">确定</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button v-if="dialogStatus === 'create'" type="primary" size="mini" @click="createOrUpdateData">创建</el-button>
        <el-button v-if="dialogStatus === 'update'" type="primary" size="mini" @click="createOrUpdateData">更新</el-button>
      </div>

    </el-dialog>


    <!-- 添加或修改团购对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="" prop="productId">-->
<!--          <el-input v-model="form.productId" placeholder="请输入" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="团购开始时间" prop="startTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.startTime"-->
<!--            type="datetime"-->
<!--            value-format="yyyy-MM-dd HH:mm:ss"-->
<!--            placeholder="请选择团购开始时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="团购结束时间" prop="endTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.endTime"-->
<!--            type="datetime"-->
<!--            value-format="yyyy-MM-dd HH:mm:ss"-->
<!--            placeholder="请选择团购结束时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="团购基础人数" prop="minimumNumber">-->
<!--          <el-input v-model="form.minimumNumber" placeholder="请输入团购基础人数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="团购已经购买人数" prop="alreadyBuyNumber">-->
<!--          <el-input v-model="form.alreadyBuyNumber" placeholder="请输入团购已经购买人数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="团购结束时购买人数未达到基础人数,是否自动退款" prop="automaticRefund">-->
<!--          <el-input v-model="form.automaticRefund" placeholder="请输入团购结束时购买人数未达到基础人数,是否自动退款" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="判断团购商品是否在活动期间" prop="status">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--              v-for="dict in dict.type.group_status"-->
<!--              :key="dict.value"-->
<!--              :label="parseInt(dict.value)"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="" prop="storageId">-->
<!--          <el-input v-model="form.storageId" placeholder="请输入" />-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import { listGroupShop, getGroupShop, delGroupShop, addGroupShop, updateGroupShop } from "@/api/group/groupShop";
import { detailGoodsByStorageId, productTreeByStorageId} from "@/api/product/storeProduct";
import {listAllStorage} from "@/api/storage/storage";

export default {
  name: "GroupShop",
  dicts: ['group_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团购表格数据
      groupShopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogStatus: 'create',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        status: undefined,
        storageId: undefined
      },
      // 表单参数
      form: {
        groupShopSkus: [],
        skuList: []
      },
      entrepotOptions: [],
      goodsOptions: [],
      goodsOption: undefined,
      groupShopUpdateSkuPriceDialog: false,
      skuForm: {},
      storages: [],
      storageMap: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "团购开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "团购结束时间不能为空", trigger: "blur" }
        ],
        minimumNumber: [
          { required: true, message: "团购基础人数不能为空", trigger: "blur" }
        ],
        automaticRefund: [
          { required: true, message: "团购结束时购买人数未达到基础人数,是否自动退款不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.listAllStorage()
  },
  methods: {
    listAllStorage() {
      listAllStorage().then(({ data }) => {
        this.storages = data
        this.storages.forEach(storage => {
          this.storageMap[storage.id] = storage.name
        })
      })
    },
    showEditStorageClick() {
      if (this.goodsOption && this.goodsOption.length > 0) {
        this.$message({
          message: '改变仓库将会清空已选商品',
          type: 'warning'
        })
      }
    },
    /** 查询团购列表 */
    getList() {
      this.loading = true;
      listGroupShop(this.queryParams).then(response => {
        this.groupShopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productId: undefined,
        minPrice: undefined,
        maxPrice: undefined,
        startTime: undefined,
        endTime: undefined,
        minimumNumber: undefined,
        alreadyBuyNumber: undefined,
        automaticRefund: 0,
        status: undefined,
        createTime: undefined,
        updateTime: undefined,
        storageId: undefined,
        groupShopSkus: [],
        skuList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    showEditStorageChange(val) {
      // 仓库切换时 清空列表
      this.form.skuList = []
      this.goodsOption = null
      this.refreshGoodsOptions()
    },
    refreshGoodsOptions() {
      productTreeByStorageId(this.form.storageId).then(response => {
        this.goodsOptions = response.data
      })
    },
    async chooseGoods(e) {
      const that = this;
      // 1. 验证是否是商品
      if (e !== undefined) {
        const tag = e[e.length - 1]
        if (this.goodsOption === undefined || this.goodsOption === null || this.goodsOption.length <= 2) {
          this.$notify.error({
            title: '提示',
            message: '请选择商品'
          })
          return false
        }

        // 2. 向后台根据商品ID获取商品信息
        this.form.productId = tag.substring(2)
        that.form.skuList = [];
        await detailGoodsByStorageId(this.form.productId,this.form.storageId).then(response => {
          const kxStockVo=response.data.kxStockVo
          const item = {};
          item.id = kxStockVo.productId
          item.title = response.data.storeName
          item.price = kxStockVo.price
          item.stock = kxStockVo.stock
          item.productGroupShopPrice = kxStockVo.price
          that.form.skuList.push(item)
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.msg + ',请重新选择'
          })
        })
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.dialogStatus = 'create'
      this.title = "添加团购";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const that = this
      this.dialogStatus = 'update'
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getGroupShop(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改团购";
        // 提取skuList中的属性并改名
        for (var i = 0; i < this.form.groupShopSkuList.length; i++) {
          const listDate = this.form.groupShopSkuList[i]
          detailGoodsByStorageId(this.form.productId,this.form.storageId).then(response => {
            const kxStockVo=response.data.kxStockVo
            const item = {};
            item.id = that.form.productId
            item.title = response.data.storeName
            item.price = kxStockVo.price
            item.stock = kxStockVo.stock
            item.productGroupShopPrice = listDate.productGroupShopPrice
            that.form.skuList = [];
            that.form.skuList.push(item)

          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.msg + ',请重新选择'
            })
          })
        }
        that.refreshGoodsOptions()
        that.form.groupShopSkus = []
        that.goodsOption = 'G_' + response.data.productId
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateGroupShop(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addGroupShop(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    createOrUpdateData() {
      debugger
      if (this.form.productId === null || this.form.productId === undefined || this.form.skuList === null || this.form.skuList === undefined || this.form.skuList.length === 0) {
        this.$notify.error({
          title: '提示',
          message: '请选择商品'
        })
        return false
      }

      if (this.form.startTime === null || this.form.startTime === undefined || this.form.endTime === null || this.form.endTime === undefined || this.form.startTime >= this.form.endTime) {
        this.$notify.error({
          title: '提示',
          message: '请选择活动时间,且开始时间小于结束时间'
        })
        return false
      }
      // 提取skuList中的属性并改名
      for (var i = 0; i < this.form.skuList.length; i++) {
        var temp = {}
        temp.productAttrId = this.form.skuList[i].id
        temp.productGroupShopPrice = this.form.skuList[i].productGroupShopPrice
        this.form.groupShopSkus.push(temp)
      }
      this.form.groupShopSkuList = this.form.groupShopSkus
      const requestForm = {
        id: this.form.id,
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        groupShopSkuList: this.form.groupShopSkuList,
        minimumNumber: this.form.minimumNumber,
        productId: this.form.productId,
        storageId: this.form.storageId,
        automaticRefund: this.form.automaticRefund
      }
      if (this.dialogStatus === 'create') {
        addGroupShop(requestForm)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '团购商品录入成功!'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '提示',
              message: response.data.msg
            })
          })
      } else if (this.dialogStatus === 'update') {
        updateGroupShop(requestForm)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '团购商品更新成功!'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '提示',
              message: response.data.msg
            })
          })
      }
      this.open = false
    },
    openSkuGroupShopPriceUpdateDialog(data) {
      this.skuForm = undefined
      this.groupShopUpdateSkuPriceDialog = true
      this.skuForm = data
    },
    skuGroupShopUpdate(data) {
      this.groupShopUpdateSkuPriceDialog = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除团购编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delGroupShop(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>
<style>
.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 100px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.gallery {
  width: 80px;
  margin-right: 10px;
}
</style>
